var {ADDRESS} = require('./config.js');
var request = require('request');
var fs = require('fs');
var qiniu = require('qiniu-js');
var remote = require('electron').remote;
const uuidv1 = remote.require('uuid/v1');
var path = require('path');

function decodeBase64Image(dataString) {
    var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
    var response = {};

    if (matches.length !== 3) {
        return new Error('Invalid input string');
    }

    response.type = matches[1];
    response.data = new Buffer(matches[2], 'base64');

    console.log("image type:" + response.type);
    return response;
}


var api = {
    accessToken:"",
    qiniuToken: "",
    qiniuDomain: "",
    qiniuTokenExpireAt:0,
    
    getQiniuToken: function() {
        var now = (new Date().getTime() / 1000);
        if (now < this.qiniuTokenExpireAt && this.qiniuDomain && this.qiniuToken) {
            //未过期
            return Promise.resolve({qiniuToken:this.qiniuToken, qiniuDomain:this.qiniuDomain});
        } else {
            return this.requestQiniuToken()
                .then((res) => {
                    this.qiniuToken = res.token;
                    this.qiniuDomain = res.domain;
                    this.qiniuTokenExpireAt = res.expires_at;

                    return Promise.resolve({qiniuToken:this.qiniuToken, qiniuDomain:this.qiniuDomain});
                });
        }
    },

    requestQiniuToken: function() {
        var url = ADDRESS + "/v1/qiniu/token?token_type=message";
        var token = this.accessToken;
        var headers = {
            "Authorization": "Bearer " + token,
        }
        var p = new Promise(function(resolve, reject) {
            $.ajax({
                url: url,
                headers:headers,
                method:'GET',
                success: function (result, status, xhr) {
                    console.log("request qiniu token success:", result);
                    resolve(result);
                },
                error: function (xhr, err) {
                    console.log("request qiniu token error:", err, xhr.status, xhr.responseText);
                    reject(err);
                }
            });
        });

        return p;
    },

    uploadImage: function(data) {
        var self = this;
        var image = decodeBase64Image(data);
        var b = new Blob([image.data], {type: image.type});
        var p = new Promise(function(resolve, reject) {
            self.getQiniuToken()
                .then((r) => {
                    var token = r.qiniuToken;
                    var domain = r.qiniuDomain;
                    var key = uuidv1();
                    if (image.type == "image/png") {
                        key += ".png";
                    } else if (image.type == "image/jpeg") {
                        key += ".jpeg";
                    }

                    var ob = qiniu.upload(b, key, token, {}, {mimeType: ["image/png", "image/jpeg", "image/gif"]});
                    var o = {
                        next: function(res) {
                            console.log("next res:", res);
                        },
                        error: function(err) {
                            console.log("error:", err);
                            reject(err);
                        },
                        complete: function(res) {
                            var imageURL = "http://" + domain + "/" + res.key;
                            console.log("complete:", res, " image url:" + imageURL);
                            resolve(imageURL);
                        }
                    };
                    ob.subscribe(o);
                });
        });

        return p;
    },



    uploadFile: function(filename, filePath, onprogress, onsuccess, onerror) {
        var self = this;
        var data = fs.readFileSync(filePath);
        var fileSize = data.length;        
        var b = new Blob([data])
        var f = new File([b], filePath);

        var p = self.getQiniuToken()
            .then((r) => {
                var token = r.qiniuToken;
                var domain = r.qiniuDomain;
                var key = uuidv1() + path.extname(filename);
                var ob = qiniu.upload(f, key, token, {}, {});
                var o = {
                    next: function(res) {
                        var p = fileSize*res.total.percent/100;
                        onprogress(p);
                        console.log("next res:", res);
                    },
                    error: function(err) {
                        console.log("error:", err);
                        onerror(err);
                    },
                    complete: function(res) {
                        var fileURL = "http://" + domain + "/" + res.key;
                        console.log("complete:", res, " file url:" + fileURL);
                        onsuccess(fileURL);
                    }
                };
                return ob.subscribe(o);
            });
        return p;
    },



    ///////////////////////////////



    uploadImage2: function(data) {
        var url = ADDRESS + "/images";
        var image = decodeBase64Image(data);
        var imageData = image.data;
        var imageType = image.type;
        var headers = {
            "Authorization": "Bearer " + this.accessToken,
            "Content-Type": imageType
        };

        var p = new Promise(function(resolve, reject) {
            $.ajax({
                url: url,
                method: "POST",
                headers: headers,
                data:imageData,
                processData:false,
                success: function (result, status, xhr) {
                    if (status == "success") {
                        console.log("url:" + result + result.src_url);
                        resolve(result.src_url);
                    } else {
                        reject(status);
                    }
                },
                error: function (xhr, err) {
                    console.log("upload image error:", err, xhr.status, xhr);
                    reject(xhr.status);
                }
            });

        });

        return p;
    },


    uploadFile3: function(filename, filePath, onprogress, onsuccess, onerror) {
        var url = ADDRESS + "/files";
        var headers = {
            "Authorization": "Bearer " + this.accessToken,
        };

        var formData = {
            file:{
                value:fs.createReadStream(filePath),
                options: {
                    filename:filename
                }
            }
        };

        var req = request.post({
                url: url,
                formData: formData,
                headers: headers
            },
            function(err, resp, body) {
                console.log("resp:", err, resp.statusCode, body);
                if (err) {
                    onerror(err);
                }
                if (resp.statusCode == 200) {
                    onsuccess(JSON.parse(body).src_url);
                } else {
                    onerror(JSON.parse(body).error)
                }
            });

        req.on('drain', () => {
            console.log("bytes written:", req.req.connection.bytesWritten);
            onprogress(req.req.connection.bytesWritten);
        });
        return req;
    },

    uploadFile2: function(filename, filePath) {
        var url = ADDRESS + "/files";
        var headers = {
            "Authorization": "Bearer " + this.accessToken,
        };

        var formData = {
            file:{
                value:fs.createReadStream(filePath),
                options: {
                    filename:filename
                }
            }
        };

        return new Promise(function(resolve, reject) {
            request.post({
                    url: url,
                    formData: formData,
                    headers: headers
                },
                function(err, resp, body) {
                    console.log("resp:", err, resp.statusCode, body);
                    if (err) {
                        reject(err);
                    }
                    if (resp.statusCode == 200) {
                        resolve(JSON.parse(body).src_url);
                    } else {
                        reject(JSON.parse(body).error)
                    }
                });
        });
    },




    //app
    requestCall: function(channelID, peerUID) {
        var url = ADDRESS + "/calls";

        var headers = {
            "Authorization": "Bearer " + this.accessToken,
            "Content-Type":"application/json"
        }
        var data = {
            channel_id:channelID,
            peer_uid:peerUID,
        };

        var p = new Promise(function(resolve, reject) {
            $.ajax({
                url: url,
                headers: headers,
                dataType: 'json',
                data: JSON.stringify(data),
                method:'POST',
                success: function (result, status, xhr) {
                    console.log("request call success:", result);
                    resolve(result);
                },
                error: function (xhr, err) {
                    console.log("request call error:", err, xhr.status, xhr.responseText);
                    reject(err);
                }
            });

        });

        return p;
    },

    hangupCall: function(channelID, peerUID) {
        var url = ADDRESS + "/calls/hangup";

        var headers = {
            "Authorization": "Bearer " + this.accessToken,
            "Content-Type":"application/json"
        }
        var data = {
            channel_id:channelID,
            peer_uid:peerUID,
        };

        var p = new Promise(function(resolve, reject) {
            $.ajax({
                url: url,
                headers: headers,
                dataType: 'json',
                data: JSON.stringify(data),
                method:'POST',
                success: function (result, status, xhr) {
                    console.log("request call success:", result);
                    resolve(result);
                },
                error: function (xhr, err) {
                    console.log("request call error:", err, xhr.status, xhr.responseText);
                    reject(err);
                }
            });

        });

        return p;
    },








    //////////////////////////////////









    login: function(username, password) {
        var url = ADDRESS + "/v1/auth/login";


        var p = new Promise(function(resolve, reject) {
            $.ajax({
                url: url,
                data: {username:username, password:password},
                method:'POST',
                success: function (result, status, xhr) {
                    console.log("request call success:", result);
                    resolve(result);
                },
                error: function (xhr, err) {
                    console.log("request call error:", err, xhr.status, xhr.responseText);
                    reject(err);
                }
            });

        });

        return p;
    },

    logout: function() {
        var url = ADDRESS + "/v1/auth/logout";
        var token = this.accessToken;
        var headers = {
            "Authorization": "Bearer " + token,
        }
        var p = new Promise(function(resolve, reject) {
            $.ajax({
                url: url,
                headers:headers,
                method:'POST',
                success: function (result, status, xhr) {
                    console.log("logout success:", result);
                    resolve(result);
                },
                error: function (xhr, err) {
                    console.log("logout error:", err, xhr.status, xhr.responseText);
                    reject(err);
                }
            });

        });

        return p;
    },

    getProfile: function() {
        var url = ADDRESS + "/v1/profile";

        var token = this.accessToken;
        var headers = {
            "Authorization": "Bearer " + token,
        }
        var p = new Promise(function(resolve, reject) {
            $.ajax({
                url: url,
                headers:headers,
                method:'GET',
                success: function (result, status, xhr) {
                    console.log("get profile success:", result);
                    resolve(result);
                },
                error: function (xhr, err) {
                    console.log("get profile error:", err, xhr.status, xhr.responseText);
                    reject(err);
                }
            });

        });

        return p;
    },

    getFriends: function() {
        var url = ADDRESS+"/v1/friends";

        var token = this.accessToken;
        var headers = {
            "Authorization": "Bearer " + token,
        }
        var p = new Promise(function(resolve, reject) {
            $.ajax({
                url: url,
                headers:headers,
                method:'GET',
                success: function (result, status, xhr) {
                    console.log("request call success:", result);
                    resolve(result);
                },
                error: function (xhr, err) {
                    console.log("request call error:", err, xhr.status, xhr.responseText);
                    reject(err);
                }
            });

        });

        return p;

    },

    getFriend: function(friendId) {
        var url = ADDRESS+"/v1/friends/" + friendId;
        
        var token = this.accessToken;
        var headers = {
            "Authorization": "Bearer " + token,
        }
        var p = new Promise(function(resolve, reject) {
            $.ajax({
                url: url,
                headers:headers,
                method:'GET',
                success: function (result, status, xhr) {
                    console.log("request call success:", result);
                    resolve(result);
                },
                error: function (xhr, err) {
                    console.log("request call error:", err, xhr.status, xhr.responseText);
                    reject(err);
                }
            });

        });

        return p;
    },

    getVersion: function() {
        var accessToken = this.accessToken;
        var url = ADDRESS + "/v1/clients";
        console.log("get client version:", url);
        var p = new Promise(function(resolve, reject) {
            $.ajax({
                url: url,
                dataType: 'json',
                headers: {"Authorization": "Bearer " + accessToken},
                success: function(data) {
                    console.log("version:", data);
                    var ver = data.windows.version;
                    var arr = ver.split(".");
                    var v = {
                        major:parseInt(arr[0]), 
                        minor:parseInt(arr[1]), 
                        build:parseInt(arr[2]), 
                        url:data.windows.url, 
                        forced:data.windows.forced
                    };
                    resolve(v);
                },
                error: function(xhr, status, err) {
                    console.error("get version:", status, err.toString(), xhr);
                    reject(err);
                },
            });
        })
        return p;
    },

    getAllGroup:function(){
        var token = this.accessToken;
        // var token = this.accessToken;
        var headers = {
            "Authorization": "Bearer " + token,
            "Content-Type": "application/json"
        }
        console.log("Authorization" + "Bearer " + token)
        var p = new Promise(function (resolve, reject) {
            //获取群组名称
            $.ajax({
                url: ADDRESS + "/v1/groups",
                dataType: 'json',
                method: 'GET',
                headers: headers,
                success: function (result, status, xhr) {
                    var data = result.groups
                    // console.log("group:", data.name, data.id, data.lvl);
                    // console.log("data+++++++" + JSON.stringify(result.groups))
                    resolve(data);
                },
                error: function (xhr, status, err) {
                    console.error("error:", status, err.toString());
                    reject(status);
                }
            });
        });
        return p;
    },
    quitGroup:function(group){
        var token = this.accessToken;
        var headers = {
            "Authorization": "Bearer " + token,
            "Content-Type": "application/json"
        }
        var p = new Promise(function (resolve, reject) {
            $.ajax({
                url: ADDRESS + "/v1/groups/"+group+"/quit",
                dataType: 'json',
                method: 'POST',
                headers: headers,
                // data:JSON.stringify({"member_ids": [memberId]}),
                success: function (result) {
                    console.log("result++++"+result)
                },
                error: function () {
                }
            });
        });
        return p;
    },
    delGroup:function(group){
        var token = this.accessToken;
        // var token = this.accessToken;
        var headers = {
            "Authorization": "Bearer " + token,
            "Content-Type": "application/json"
        }
        var p = new Promise(function (resolve, reject) {
            $.ajax({
                url: ADDRESS + "/v1/groups/"+group,
                dataType: 'json',
                method: 'DELETE',
                headers: headers,
                // data:JSON.stringify({"member_ids": [memberId]}),
                success: function (result) {
                    console.log("result++++"+result)
                },
                error: function () {
                }
            });
        });
        return p;
    },
    addGroupMembers:function(group,memberIds){
        var token = this.accessToken;
        // var token = this.accessToken;
        var headers = {
            "Authorization": "Bearer " + token,
            "Content-Type": "application/json"
        }
        var p = new Promise(function (resolve, reject) {
            $.ajax({
                url: ADDRESS + "/v1/groups/"+group+"/members",
                dataType: 'json',
                method: 'POST',
                headers: headers,
                data:JSON.stringify({"member_ids": memberIds}),
                success: function (result) {
                },
                error: function () {
                }
            });
        });
        return p;
    },
    newFriends:function(new_friend,status){
        var token = this.accessToken;
        // var token = this.accessToken;
        var headers = {
            "Authorization": "Bearer " + token,
            "Content-Type": "application/json"
        }
        // var p = new Promise(function (resolve, reject) {
            $.ajax({
                url: ADDRESS + "/v1/new_friends/"+new_friend,
                dataType: 'json',
                method: 'PATCH',
                headers: headers,
                data:JSON.stringify({"status": status}),
                success: function (result) {
                    // console.log("result++++"+result)
                },
                error: function () {
                }
            });
        // });
        // return p;
    },
    delGroupMember:function(group,memberId){
        var token = this.accessToken;
        // var token = this.accessToken;
        var headers = {
            "Authorization": "Bearer " + token,
            "Content-Type": "application/json"
        }
        var p = new Promise(function (resolve, reject) {
            $.ajax({
                url: ADDRESS + "/v1/groups/"+group+"/members",
                dataType: 'json',
                method: 'DELETE',
                headers: headers,
                data:JSON.stringify({"member_ids": [memberId]}),
                success: function (result) {
                    // console.log("result++++"+result)
                },
                error: function () {
                }
            });
        });
        return p;
    },
    getGroup: function(groupID) {
        var p = Promise.all([this.getGroupInfo(groupID), this.getGroupMembers(groupID)])
                .then((values) => {
                    var group = values[0];
                    group.id = parseInt(group.id);
                    var groupMembers = values[1];
                    group.members = groupMembers.map(function(item) {
                        var t = Object.assign({}, item);
                        t.uid = parseInt(item.id);
                        t.avatar = item.portrait;
                        t.name = item.nickname;
                        return t;
                    })
                    console.log("get gggg:", group);
                    return group;
                });
        return p;
    },

    getGroupInfo: function(groupID) {
        var token = this.accessToken;
        console.log("group id:", groupID, " access token:", token);
        var p = new Promise(function(resolve, reject) {
            //获取群组名称
            $.ajax({
                url: ADDRESS + "/v1/groups/" + groupID,
                dataType: 'json',
                headers: {"Authorization": "Bearer " + token},
                success: function(result, status, xhr) {
                    var data = result;
                    console.log("group:", data);
                    resolve(data);
                },
                error: function(xhr, status, err) {
                    console.error("error:", status, err.toString());
                    reject(status);
                }
            });
        });
        return p;
    },

    getGroupMembers: function(groupID) {
        var token = this.accessToken;
        var p = new Promise(function(resolve, reject) {
            //获取群组名称
            $.ajax({
                url: ADDRESS + "/v1/groups/" + groupID + "/members",
                dataType: 'json',
                headers: {"Authorization": "Bearer " + token},
                success: function(result, status, xhr) {
                    var data = result.members;
                    console.log("group members:", data);
                    resolve(data);
                },
                error: function(xhr, status, err) {
                    console.error("error:", status, err.toString());
                    reject(status);
                }
            });
        });
        return p;
    },


    reverseGeocodeLocation: function(longitude, latitude) {
        return new Promise(function(resolve, reject) {
            //高德接口文档地址：http://lbs.amap.com/api/webservice/guide/api/georegeo/?
            var url = "http://restapi.amap.com/v3/geocode/regeo?key=66b4a0d40d9ec78de80a6bf6584d61f8&location=" + longitude + ',' + latitude;
            $.ajax({
                url: url,
                dataType: 'json',
                method:'GET',
                success: function (result, status, xhr) {
                    if (status == "success") {
                        var addr = result.regeocode.addressComponent;
                        var a = addr.city + addr.district + addr.township;
                        resolve(a);
                    } else {
                        reject(result)
                    }
                },
                error: function (xhr, err) {
                    console.log("refresh qrcode error:", err, xhr.status, xhr);
                    reject(err);
                }
            });

        });

    },



};

module.exports = api;
